/**
 * 
 */
package core;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.URL;
import java.net.URLConnection;
import java.util.Observable;

import model.ThreadDownloadedInfo;
/**
 * @author Ken
 *
 */
public class DownloadThread extends Observable implements Runnable {
	public DownloadThread(int index, URL url, int offset, int size, String fileName) {
		id = index;
		this.url = url;
		this.offset = offset;
		this.size = size;
		this.file = fileName;
	}

	@Override
	public void run() {
		final int l = 512 * 1024;
		byte[] buffer = new byte[l];
		int count = 0;

		BufferedInputStream bis = null;
		RandomAccessFile fos = null;
		try {
			URLConnection conn = (URLConnection)url.openConnection();
			conn.setRequestProperty("Range", "bytes=" + offset + "-" + (offset + size - 1));
			conn.connect();
		    bis = new BufferedInputStream(conn.getInputStream());
			fos = new RandomAccessFile(file, "rw");
			fos.seek(offset);
			while (true) {
				count = bis.read(buffer, 0, l);
				if (count > 0)
				{											
					fos.write(buffer, 0, count);
					ThreadDownloadedInfo info = new ThreadDownloadedInfo(id, count);
					setChanged();
					notifyObservers(info);
				}
				else
					break;
			}
			ThreadDownloadedInfo info = new ThreadDownloadedInfo(id, -1);
			setChanged();
			notifyObservers(info);
			fos.close();
			bis.close();		
		}
		catch (IOException e) {				
			e.printStackTrace();
		}
	}
	
	int offset;
	int size;
	URL url;
	String file;
	int id;
}
